package org.yuanqiframework.yuanqi.boot.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.xss.core.XssCleanIgnore;
import org.springframework.web.bind.annotation.*;
import org.yuanqiframework.yuanqi.boot.sys.service.SysFormService;
import org.yuanqiframework.yuanqi.boot.sys.dto.SysFormDTO;
import org.yuanqiframework.yuanqi.boot.sys.entity.SysForm;
import org.yuanqiframework.yuanqi.core.utils.BeanUtils;
import org.yuanqiframework.yuanqi.web.controller.BaseController;
import org.yuanqiframework.yuanqi.web.entity.AjaxResult;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/sys/form")
public class FormController extends BaseController {
    @Resource
    private SysFormService sysFormService;

    @GetMapping("saveCheck/{id}")
    public AjaxResult<?> saveCheck(@PathVariable String id) {
        return success(sysFormService.count(new LambdaQueryWrapper<SysForm>()
                .eq(SysForm::getId, id)));
    }

    @XssCleanIgnore
    @PostMapping("save")
    public AjaxResult<?> save(@Valid @RequestBody SysFormDTO sysFormDTO) {
        SysForm sysForm = new SysForm();
        BeanUtils.copyProperties(sysFormDTO, sysForm);
        return toAjax(sysFormService.saveOrUpdate(sysForm));
    }

    @GetMapping("list")
    public AjaxResult<List<SysForm>> list() {
        List<SysForm> list = sysFormService.list(new LambdaQueryWrapper<SysForm>()
                .select(SysForm::getId,
                        SysForm::getTitle,
                        SysForm::getDescription
                ));
        return success(list);
    }

    @GetMapping("load/{id}")
    public AjaxResult<?> load(@PathVariable String id) {
        SysForm sysForm = sysFormService.getOne(new LambdaQueryWrapper<SysForm>()
                .eq(SysForm::getId, id));
        if(sysForm==null){
            return error();
        }
        String data = sysForm.getData();
        JSONObject jsonObject = JSONObject.parseObject(data);
        return success(jsonObject);
    }
}
